//
//  HNOrderDetailController.m
//  baidaifu
//
//  Created by 朱传正 on 2016/12/24.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNOrderDetailController.h"
#import "HNPayTypeController.h"
#import "ChatViewController.h"
#import "HNApplyRefundController.h"
#import "CookingbarCommentController.h"
#import "OrderDetailController.h"

@interface HNOrderDetailController ()<HNPayTypeControllerDelegate>


@property (nonatomic,strong)NSDictionary *orderDic;
@property (nonatomic,strong)NSDictionary *goodsDic;


@end

@implementation HNOrderDetailController

-(void)viewWillAppear:(BOOL)animated{
      [self getOrderDetail];
    
    //设置界面状态
//    [self setOrderState];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单详情";
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
}

-(void)initData{
  
}


- (IBAction)cancelOrderAction:(UIButton *)sender {
    
    
    HNApplyRefundController *applyRefundVC = [[HNApplyRefundController alloc]init];
    applyRefundVC.orderDic = _orderDic;;

    [self.navigationController pushViewController:applyRefundVC animated:YES];
    
    
}

- (IBAction)payAction:(UIButton *)sender {
    
    
    HNPayTypeController *payTypeVC = [[HNPayTypeController alloc]init];
    payTypeVC.orderSn = _orderSn;
    payTypeVC.orderDic = _orderDic;
    payTypeVC.payTypeDelagete = self;
    [self.navigationController pushViewController:payTypeVC animated:YES];
}


- (IBAction)flashConsult:(UIButton *)sender {
    if (_isChat) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",_orderSn,@"orderSn", nil];
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_consultService_start parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSArray *urerList = [data objectForKey:@"obj"];
            NSLog(@"------obj = %@",urerList);
            
            //开始聊天
            NSString *sellerUsername = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"sellerUsername"]];
            
            if(sellerUsername.length <= 1){
                [self showHint:@"无此用户"];
            }
            NSString *loginName = [[EMClient sharedClient] currentUsername];
            if ([sellerUsername isEqualToString:loginName]) {
                [self showHint:@"不能和自己聊天"];
                return;
            }else{
                
                [self setsellerUsername:sellerUsername];
                
            }

            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }

             [self showHint:info];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取用户信息失败"];
    }];
    
    
    
   
    
}


- (IBAction)priceOrderAction:(UIButton *)sender {
    CookingbarCommentController *commentVC = [[CookingbarCommentController alloc]init];
    NSString *orderSn = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"orderSn"]];
    commentVC.orderSn = orderSn;
    [self.navigationController pushViewController:commentVC animated:YES];
    
    
}


-(void)setsellerUsername:(NSString *)mobile {
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:mobile,@"mobile", nil];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_userInfoList_tel parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSArray *urerList = [data objectForKey:@"obj"];
            NSLog(@"------obj = %@",urerList);
            
            NSDictionary *userInfo = urerList[0];

       
            NSString *nickname = nil;
            NSString *photo = nil;
            NSString *hnLoginName = nil;
      
            nickname = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"nickname"]];

            photo = [NSString stringWithFormat:@"%@%@",url_Base,[userInfo objectForKey:@"photo"]];

            hnLoginName = mobile;
            NSMutableDictionary *peopleUserInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:hnLoginName,@"hnLoginName" ,nil];
            [peopleUserInfo setObject:nickname forKey:@"nickname"];
            [peopleUserInfo setObject:photo forKey:@"photo"];
            NSLog(@"%@",peopleUserInfo);
            
            [AppConfig savePeopleInfo:peopleUserInfo];
            
            ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:mobile conversationType:EMConversationTypeChat];

            chatController.doctorUsername = mobile;
            
            if([AppConfig isNULL:nickname]){
                chatController.title = mobile;
            }else{
                chatController.title = nickname;
            }
            
              [self.navigationController pushViewController:chatController animated:YES];
            
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            NSLog(@"msg = %@",info);
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取用户信息失败"];
    }];

}



- (IBAction)consultDoctorBtn:(UIButton *)sender {
    
    //开始聊天
    NSString *sellerUsername = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"sellerUsername"]];
    
    if(sellerUsername.length <= 1){
        [self showHint:@"无此用户"];
    }
    NSString *loginName = [[EMClient sharedClient] currentUsername];
    if ([sellerUsername isEqualToString:loginName]) {
        [self showHint:@"不能和自己聊天"];
        return;
    }else{
        
        [self setsellerUsername:sellerUsername];
        
    }

}



-(void)drawView{
    
    if (_isService) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"xiangyou.png"] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
    }

    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
}

-(void)backAction{
    int index=(int)[[self.navigationController viewControllers]indexOfObject:self];
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:index-3]animated:YES];
}

#pragma mark - 设置订单状态
-(void)setOrderState{
    //0：去支付 1：申请退款、立即咨询 2：申请退款 3：订单介绍
    if ([_orderState isEqualToString:@"0"]) {
        [_flasgConsultBtn setHidden:YES];
        [_cancelBtn setHidden:YES];
        [_payBtn setHidden:NO];
        [_cancelBtnLarge setHidden:YES];
        [_priceBtn setHidden:YES];
        [_consultDoctorBtn setHidden:YES];
        
        [_leftLine setBackgroundColor:[UIColor grayColor]];
        [_rightLine setBackgroundColor:[UIColor grayColor]];
    }else if([_orderState isEqualToString:@"1"] || [AppConfig isNULL:_orderState]){
        [_flasgConsultBtn setHidden:NO];
        [_cancelBtn setHidden:NO];
        [_payBtn setHidden:YES];
        [_cancelBtnLarge setHidden:YES];
        [_priceBtn setHidden:YES];
        [_consultDoctorBtn setHidden:YES];
        
        [_zhifuImageView setHighlighted:YES];
        
        [_leftLine setBackgroundColor:RGB(242, 142, 0)];
        [_rightLine setBackgroundColor:[UIColor grayColor]];
    }else if([_orderState isEqualToString:@"11"]){
        [_flasgConsultBtn setHidden:YES];
        [_cancelBtn setHidden:YES];
        [_payBtn setHidden:YES];
        [_cancelBtnLarge setHidden:NO];
        [_priceBtn setHidden:YES];
        [_consultDoctorBtn setHidden:NO];
        
        [_zhifuImageView setHighlighted:YES];
        [_quickImageView setHighlighted:YES];
        
        [_leftLine setBackgroundColor:RGB(242, 142, 0)];
        [_rightLine setBackgroundColor:RGB(242, 142, 0)];
    }else if([_orderState isEqualToString:@"3"]){
        [_flasgConsultBtn setHidden:YES];
        [_cancelBtn setHidden:YES];
        [_payBtn setHidden:YES];
        [_cancelBtnLarge setHidden:YES];
        [_priceBtn setHidden:NO];
        [_consultDoctorBtn setHidden:YES];
        
        [_zhifuImageView setHighlighted:YES];
        [_quickImageView setHighlighted:YES];
        [_finishImageView setHighlighted:YES];
        
        [_leftLine setBackgroundColor:RGB(242, 142, 0)];
        [_rightLine setBackgroundColor:RGB(242, 142, 0)];
    }

}

#pragma mark - 获取订单信息
-(void)getOrderDetail{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    
    [param setObject:_orderSn forKey:@"orderSn"];
    
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_order_detail parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取订单详情失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            _orderDic = [NSDictionary dictionaryWithDictionary:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",_orderDic);
            _goodsDic = [_orderDic objectForKey:@"goods"][0];
              NSLog(@"------goods = %@",_goodsDic);
            
            
            _orderNo.text = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"orderSn"]];
            _orderName.text = [NSString stringWithFormat:@"%@",[_goodsDic objectForKey:@"goodsName"]];
            _orderPersonName.text = [NSString stringWithFormat:@"%@",[_goodsDic objectForKey:@"goodsName"]];
            _orderTime.text = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"createTime"]];
            _orderPrice.text = [NSString stringWithFormat:@"¥%@",[_orderDic objectForKey:@"money"]];
            
            _orderState = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"status"]];
            
       
//
            [self setOrderState];
            
            NSString *buyerHasComment = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"buyerHasComment"]];
            NSLog(@"%@",buyerHasComment);
            
            if ([buyerHasComment isEqualToString:@"1"]) {
                [_priceBtn setHidden:YES];
                
            }
            
            
        }else{
            
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取订单详情失败"];
    }];
    
}

#pragma mark - HNPayTypeControllerDelegate
-(void)HNPayTypeControllerBackChangeOrderState{
    [self getOrderDetailToChangeOrderState];
}

-(void)getOrderDetailToChangeOrderState{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    
    [param setObject:_orderSn forKey:@"orderSn"];
    
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_order_detail parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSLog(@"responseObject = %@",responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取订单详情失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            _orderDic = [NSDictionary dictionaryWithDictionary:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",_orderDic);
            _goodsDic = [_orderDic objectForKey:@"goods"][0];
            NSLog(@"------goods = %@",_goodsDic);
            
            
//            _orderNo.text = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"orderSn"]];
//            _orderName.text = [NSString stringWithFormat:@"%@",[_goodsDic objectForKey:@"goodsName"]];
//            _orderPersonName.text = [NSString stringWithFormat:@"%@",[_goodsDic objectForKey:@"goodsName"]];
//            _orderTime.text = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"createTime"]];
//            _orderPrice.text = [NSString stringWithFormat:@"¥%@",[_orderDic objectForKey:@"money"]];
//            
            _orderState = [NSString stringWithFormat:@"%@",[_orderDic objectForKey:@"status"]];
            [self setOrderState];
            
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取订单详情失败"];
    }];
    
}



@end
